
package com.team2.cyber_eye;

import java.io.File;
import java.util.List;

import com.team2.cyber_eye.ActivityHelpers.Util;
import com.team2.shared.HistoryItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class HistoryActivity extends CyberActivity {

    private static final int DELETE_MENU_ITEM = 0;

    private ListView historyListView;
    
    HistoryItem item;
    
    AdapterView.AdapterContextMenuInfo info;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState, R.layout.activity_history, "HISTORY");       
        initUi();
    }

    private void initUi() {
    	historyListView = (ListView) findViewById(R.id.list);
        historyListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parentView, View view, int position, long id) {
                     ItemClick(position);       
            }
        });
        
        registerForContextMenu(historyListView);
    }
    
    private void ItemClick(int position){
    	try
		{
    		item = (HistoryItem) Home.historyListAdapter.getItem(position);
            
            if(item != null){
            	 Intent intent = new Intent(HistoryActivity.this, SearchByText.class);
            	 
            	 if(item.getIqeOrBarcode().equals("iqe")){
            		 
            		 if(item.getImageUri().length() > 0){
            			 Uri uri = Uri.parse(item.getImageUri());
            			 intent.setData(uri);
            		 }
            	 }else if(item.getIqeOrBarcode().equals("barcode")){
            		 
            		 intent.putExtra("photo", item.getThumb());
            	}
		          
 	        	intent.putExtra("text", item.getLabel());
 	        	intent.putExtra("FromIQE", "yes"); 	        	
 	        	intent.putExtra("iqeOrBarcode", item.getIqeOrBarcode());
 	        	intent.putExtra("fromHistory", "yes");
 	        	
 	        	this.startActivity(intent);
            } 	
		}
		catch (Exception ex)
		{
			Util.DisplayError(this, "Error processing selected item", ex);
		}
    }

    @Override
    public void onResume() {
        historyListView.setAdapter(Home.historyListAdapter);
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
       if (v.getId() == R.id.list) {
    	   super.onCreateContextMenu(menu, v, menuInfo);
    	   ContextThemeWrapper mTheme = new ContextThemeWrapper(this,
    		        R.style.Theme_MyDialog);
    	   
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
            item = (HistoryItem) Home.historyListAdapter
                    .getItem(info.position /* -1 subtracting header view-item */ );
            
            new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.Theme_MyDialog))
            .setIcon(android.R.drawable.ic_delete)
            .setTitle(item.getLabel())
            .setMessage("Are you sure you want to remove this item?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	
	            	HistoryItem removedItem = Home.historyListAdapter
	                        .removeItem(info.position/* - 1/* subtracting header view-item */);
	                Home.historyListAdapter.notifyDataSetChanged();
	            	
	            	List<HistoryItem> history = Home.getHistory();
	            	
	            	Home.historyItemDao.saveAll(history);
	            	Toast.makeText(getApplicationContext(), "'" + removedItem.getLabel() + "' removed from the history",
	                        Toast.LENGTH_SHORT).show();
	            	
	            	DeleteFileFromMemory(item.getImageUri());
	            	
	            	if(history.size() == 0){
						finish();
					}
	            }

            })
            .setNegativeButton("No", null)
            .show();
        }
    }
    
    private void DeleteFileFromMemory(String uri){
    	try{
    		
    		String originalPath = uri.replace("file://", "");
        	
    		File newFile = new File(originalPath);
        	
    		if(newFile != null && newFile.exists()){
        		newFile.delete();
        	}
        	
        	if(Util.getIqeBitmapFile() != null &&
        			Util.getIqeBitmapFile().exists()){
        		Util.getIqeBitmapFile().delete();
        	}
    	}catch(Exception ex){
    		Util.DisplayMessage(getApplicationContext(), "Error deleting file from memory");
    	}  	 	
    }

    @Override
    public boolean onContextItemSelected(MenuItem menuItem) {
        /*AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuItem
                .getMenuInfo();
        if (menuItem.getItemId() == DELETE_MENU_ITEM) {
            HistoryItem removedItem = Home.historyListAdapter
                    .removeItem(info.position - 1/* subtracting header view-item );
            Home.historyListAdapter.notifyDataSetChanged();
            Toast.makeText(this, "'" + removedItem.getLabel() + "' removed from the history",
                    Toast.LENGTH_SHORT).show();
        }*/
        return true;
    }
}
